﻿using System;
using System.IO;
using System.Threading;

namespace HtmlToPic
{
    public partial class HtmlToPic : Form
    {
        private readonly CefSharp.WinForms.ChromiumWebBrowser _webCom1 = null;
        private FileInfo _file;
        private readonly bool _isOneTime;
        private bool _loaded;
        private readonly object _lockO = new object();
        private readonly ILog _log;
        private string _savePath = "";
        private string _url;

        public HtmlToPic()
        {
        }

        public HtmlToPic(string[] s)
        {
            _log = LogManager.GetLogger(typeof(HtmlToPic));
            InitializeComponent();

            CefSettings settings = new CefSettings();
            var cache = Environment.CurrentDirectory + @"\cookie";
            settings.RemoteDebuggingPort = 8080;
            settings.CachePath = cache;
            Cef.Initialize(settings);

            _webCom1 = new CefSharp.WinForms.ChromiumWebBrowser("http://www.baidu.com") { Dock = DockStyle.Fill };
            panel1.Controls.Add(_webCom1);

            _webCom1.LoadingStateChanged += OnLoadingStateChanged;
            if (s.Length > 1)
            {
                _isOneTime = true;
                _savePath = s[1];
                _webCom1.Load(s[0]);
            }
            else
            {
                //监控文件变化
                var watchPath = Environment.CurrentDirectory + @"\Watch";
                if (!Directory.Exists(watchPath))
                    Directory.CreateDirectory(watchPath);
                FileSystemWatcher watcher = new FileSystemWatcher();
                watcher.Path = Environment.CurrentDirectory + @"\Watch";

                watcher.Created += FileCreated;
                watcher.EnableRaisingEvents = true;
            }
            _log.Info("开始执行！");
        }

        private void FileCreated(object sender, FileSystemEventArgs e)
        {
            lock (_lockO)
            {
                try
                {
                    if (e.Name.Contains(".txt"))
                    {
                        _log.Info("检测到文件" + e.FullPath);
                        _file = new FileInfo(e.FullPath);
                        Thread.Sleep(100);
                        _url = File.ReadAllText(_file.FullName);
                        var path = new DirectoryInfo(Environment.CurrentDirectory);
                        if (path.Parent == null)
                        {
                            
                        }
                        _savePath = path.Parent.Parent.FullName + @"\TempFiles\" + _file.Name.Replace(".txt", ".png");
                        _webCom1.Load(_url);
                    }
                }
                catch (Exception ex)
                {
                    _log.Error("FileCreated", ex);
                }
            }
        }

        private void OnLoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
        {
            try
            {
                if (!e.IsLoading && !_loaded)
                {
                    _log.Info("开始处理" + _savePath + _url);
                    _loaded = true;
                    var response = _webCom1.EvaluateScriptAsync(@"var url;
                                                                    html2canvas($('body'), {
                                                                            onrendered: function(canvas) {
                                                                                        url = canvas.toDataURL();
                                                                                    }
                                                                                });
                                                                    url;
                                                                ").ContinueWith(i =>
                    {
                        while (true)
                        {
                            if (i.Result.Result != null)
                                break;
                            i = _webCom1.EvaluateScriptAsync(@" url; ");
                            i.Wait(1000);
                            Thread.Sleep(100);
                        }
                        var arr2 =
                            Convert.FromBase64String(i.Result.Result.ToString().Replace("data:image/png;base64,", ""));
                        using (var ms2 = new MemoryStream(arr2))
                        {
                            System.Drawing.Bitmap bmp2 = new System.Drawing.Bitmap(ms2);
                            bmp2.Save(_savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                            bmp2.Dispose();
                            _log.Info("保存完成" + _savePath);
                        }
                        if (_file != null && File.Exists(_file.FullName))
                        {
                            File.SetAttributes(_file.FullName, FileAttributes.Normal);
                            File.Delete(_file.FullName);
                        }
                        _loaded = false;
                        if (_isOneTime)
                            Application.Exit();
                    });
                }
            }
            catch (Exception ex)
            {
                _log.Error("OnLoadingStateChangedAsync", ex);
            }
        }

        private void HtmlToPic_VisibleChanged(object sender, EventArgs e)
        {
        }

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void 显示ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Location = new Point(50, 50);
        }

        private void 隐藏ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Location = new Point(1000000, 1000000);
        }
    }
}